const pool  = require('../config/db');

const articleService = {
  // 单个文章
  getArticleDetail: async (id) => {
    try {
      const sql = 'SELECT * FROM article WHERE id = ?';
      const [result] = await pool.execute(sql,[id]);
      return result?.[0] || {};
    } catch (error) {
      throw new Error('获取文章失败');
    }
  },
  // 文章列表
  getArticleList: async (params) => {
    try {
      const { title = '', tagType = null, pageIndex = 1, pageSize = 10 } = params || {};
     
      const conditions = [];
      let queryParams = [];

      // 2. 动态构建查询条件
      if (title) {
        conditions.push('title LIKE ?');
        queryParams.push(`%${title}%`);
      }

      if (tagType !== null && tagType !== undefined) {
        conditions.push('tag.id = ?');
        queryParams.push(tagType);
      }

      // 3. 生成 WHERE 子句（无条件时不添加 WHERE）
      const whereClause = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';

      // 4. 统一 SQL 语句
      let sql = `select article.id, title, content, 
                    article.created_at, 
                    articleImgUrl, 
                    contentDesc, 
                    article.html_content as htmlContent,
                    tag.id as tagId, 
                    tag.name as tagName
                    from article left join tag on tag.id = article.tagId
                    ${whereClause}
                    order by article.created_at desc`;
      const offset = (pageIndex - 1) * pageSize;
      const limit = pageSize;
      sql += ` LIMIT ${limit} OFFSET ${offset}`;

      //返回记录总条数
      const countSql = `SELECT COUNT(*) as total FROM article left join tag on tag.id = article.tagId ${whereClause}`;
      const [countResult] = await pool.execute(countSql, [...queryParams]);
      const total = countResult[0].total;

      const [result] = await pool.execute(sql, queryParams);
      return {
        result,
        total,
      };
    } catch (error) {
      console.log(error);
      
      throw new Error('获取文章列表失败');
    }
  },
  // 创建文章
  createArticle: async (params) => {
    const { userId, title, content, contentDesc,htmlContent, status } = params;
    try {
      const sql = 'INSERT INTO article (user_id, title, content, contentDesc, html_content, status, view_count) VALUES (?, ?, ?, ?, ?, ?, 0)';
      const [result] = await pool.execute(sql, [userId, title, content, contentDesc, htmlContent, status]);
      if (result.affectedRows > 0) {
        return {};
      }else{
        const error = new Error('创建失败');
        error.statusCode = 400;
        throw error;
      }
    } catch (error) {
      console.log(error);
      throw error;
    }
  },
  // 更新文章
  updateArticle: async (params) => {
    const { title, content, contentDesc, htmlContent, status, id } = params;
    try {
      const sql = 'UPDATE article SET title = ?, content = ?, contentDesc = ?, html_content = ?, status = ? WHERE id = ?';
      const [result] = await pool.execute(sql, [title, content, contentDesc, htmlContent, status, id]);
      if (result.affectedRows > 0) {
        return {};
      }else{
        const error = new Error('更新失败');
        error.statusCode = 400;
        throw error;
      }
    } catch (error) {
      throw error;
    }
  },

  // 删除文章
  deleteArticle: async (params) => {
    const { id } = params;
    try {
      const sql = 'DELETE FROM article WHERE id = ?';
      const [result] = await pool.execute(sql, [id]);
      if (result.affectedRows > 0) {
        return {};
      }else{
        const error = new Error('删除失败');
        error.statusCode = 400;
        throw error;
      }
    } catch (error) {
      throw error;
    }
  },

  deleteBatchArticles: async (params) => {
    const { ids } = params;
    try {
      const placeholders = ids.map(() => '?').join(',');
      const sql = `DELETE FROM article WHERE id IN (${placeholders})`;
      const [result] = await pool.execute(sql, ids);
      if (result.affectedRows > 0) {
        return {};
      }else{
        const error = new Error('删除失败');
        error.statusCode = 400;
        throw error;
      }
    } catch (error) {
      throw error;
    }
  },

}

module.exports = articleService